package logic

import (
	"commodity/model/cache"
	"context"
	"fmt"
	"strconv"

	"commodity/commodityrpc/commodityrpc"
	"commodity/commodityrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *commodityrpc.CartListRequest) (*commodityrpc.CartListResponse, error) {
	// todo: add your logic here and delete this line

	key := fmt.Sprintf("cart:%d:*", in.UserId)
	keys := cache.Rdb.Keys(l.ctx, key).Val()

	tuile := 0.0
	var care []*commodityrpc.CartList

	for _, k := range keys {
		val := cache.Rdb.HGetAll(l.ctx, k).Val()
		id, _ := strconv.Atoi(val["id"])
		price, _ := strconv.ParseFloat(val["price"], 64)
		quantity, _ := strconv.ParseInt(val["quantity"], 10, 64)

		strSum := price * float64(quantity)
		tuile += strSum

		item := commodityrpc.CartList{
			Id:       int64(id),
			Name:     val["name"],
			Price:    float32(price),
			Image:    val["image"],
			Quantity: quantity,
		}
		care = append(care, &item)
	}
	return &commodityrpc.CartListResponse{
		Total: float32(tuile),
		List:  care,
	}, nil
}
